﻿using Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Newtonsoft.Json;
using System.Text;

namespace Sigma.Admin.API.Authoriza.Handler
{
    public class ApiResponeAuthResultHandler: IAuthorizationMiddlewareResultHandler
    {
        private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();

        public async Task HandleAsync(
            RequestDelegate next,
            HttpContext context,
            AuthorizationPolicy policy,
            PolicyAuthorizationResult authorizeResult)
        {

            // If the authorization was forbidden and the resource had a specific requirement,
            // provide a custom 404 response.
            if (authorizeResult.Forbidden)
            {
                // Return a 404 to make it appear as if the resource doesn't exist.
                context.Response.StatusCode = StatusCodes.Status403Forbidden;

                var apiResponse = JsonConvert.SerializeObject(new ApiResponse("403质询，您无权访问"));
                await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(apiResponse));
                return;
            }
            if(authorizeResult.Challenged)
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                var apiResponse = JsonConvert.SerializeObject(new ApiResponse("401质询，请先登录"));
                await context.Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(apiResponse));
                return;
            }

            // Fall back to the default implementation.
            await defaultHandler.HandleAsync(next, context, policy, authorizeResult);
        }
    }
}

